package com.example.project2.server.Impl;


import com.example.project2.entity.UserTable;
import com.example.project2.mapper.UserMapper;
import com.example.project2.server.UserTableServer;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service//标记一个类作为服务层
public class UsertableServerImpl implements UserTableServer {
    @Autowired
    UserMapper userTableMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    //主要作用是将方法的返回值缓存起来，以便在后续调用时可以直接从缓存中获取结果

    // 使用 @Cacheable 注解实现自动缓存
    @Cacheable(value = "users", key = "#id")
    public UserTable queryid(int id) {
        return userTableMapper.queryid(id);
    }

    // 使用 RedisTemplate 手动管理缓存
    public UserTable getUserById(int id) {
        String key = "users:" + id;
        Object cache = redisTemplate.opsForValue().get(key);
        if (cache != null) {
            System.out.println("Cache hit for key: " + key);
            return (UserTable) cache;
        }
        System.out.println("Cache miss for key: " + key);
        UserTable user = userTableMapper.queryid(id);
        if (user != null) {
            System.out.println("Storing user in cache with key: " + key);
            System.out.println(user);
            redisTemplate.opsForValue().set(key, user);
        }
        return user;
    }


}
